package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.HealthException;
import com.itheima.health.pojo.Permission;
import com.itheima.health.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;


    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    @Override
    public List<Integer> findPermissionIdsByRoleId(int roleId) {

        return permissionDao.findPermissionIdsByRoleId(roleId);
    }


    @Override
    public void addPermission(Permission permission) {
        permissionDao.addPermission(permission);
    }

    @Override
    public PageResult<Permission> findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())){
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        Page<Permission>page=permissionDao.findByCondition(queryPageBean.getQueryString());
        PageResult<Permission> pageResult=new PageResult<>(page.getTotal(),page.getResult());
        return pageResult;
    }

    @Override
    public Permission findById(int id) {
        Permission permission=permissionDao.findById(id);
        return permission;
    }

    @Override
    public void updatePermission(Permission permission) {
        permissionDao.updatePermission(permission);
    }

    @Override
    @Transactional
    public void deletePermissionById(int id) {
        int count=permissionDao.findCountRolePermission(id);
        if (count>0){
            throw new HealthException("已被角色使用");
        }else {
            permissionDao.deletePermissionById(id);
        }
    }

    @Override
    public List<Permission> findPermisson() {
        return permissionDao.findPermission();
    }
}
